/*
 * @Author: shengduiliang 1107722390@qq.com
 * @Date: 2024-05-05 13:11:09
 * @LastEditors: shengduiliang 1107722390@qq.com
 * @LastEditTime: 2024-05-06 00:03:30
 * @FilePath: /treasure/src/pages/treasury/create/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { View } from '@tarojs/components'
import { useState } from 'react'
import Taro from '@tarojs/taro';
import { Card, Form, ImagePicker, PrimaryButton, TextArea, TextInput } from '@/ui-components'
import { dialog } from '@/utils'
import { TreasuryCreateParam, createTreasury } from '@/network/treasury';
import to from 'await-to-js';
import './index.scss'

const checkTreasuryLogo = (treasuryLogo ?: string) => {
  return new Promise((resolve, reject) => {
    if (!treasuryLogo) {
      Dialogconfirm({
        content: '您确定使用默认图标作为您的宝库图标吗?',
        onConfirm: () => {
          resolve(true)
        },
        onCancel: () => {
          reject()
        }
      })
    } else {
      resolve(true)
    }
  })
}

type TreasuryCreateState = Partial<TreasuryCreateParam>

export default function TreasuryCreate() {

  const [treasury, setTreasury] = useState<TreasuryCreateState>({})

  const canNext = () => {
    return !!treasury.treasuryName && !!treasury.treasuryDescription
  }

  const handleCreate = async () => {
    let [err] = await to(checkTreasuryLogo(treasury.treasuryLogo))
    if (err) return
    [err] = await to(createTreasury(treasury as TreasuryCreateParam))
    if (err) return
    Taro.showToast({ title: '创建宝库成功' })
    Taro.reLaunch({ url: '/pages/home/index' })
  }

  return (
    <View className='treasury-create'>
      <Card>
        <Form>
          <TextInput
            value={treasury.treasuryName}
            onChange={(treasuryName) => setTreasury({ ...treasury, treasuryName })}
            label='宝库名称'
            placeholder='请输入宝库名称'
            maxlength={10}
          />
          <ImagePicker
            images={treasury.treasuryLogo ? [treasury.treasuryLogo] : []}
            onChange={(images) => setTreasury({ ...treasury, treasuryLogo: images[0] })}
            title='宝库图标'
            subTitle='不传以默认图标为主'
            count={1}
          />
          <TextArea
            value={treasury.treasuryDescription}
            onChange={(treasuryDescription) => setTreasury({ ...treasury, treasuryDescription })}
            label='宝库描述'
            placeholder='请输入宝库描述'
            maxlength={50}
          />

        </Form>
      </Card>
      <PrimaryButton
        text='创建宝库'
        disabled={!canNext()}
        onClick={handleCreate}
      />
    </View>
  )
}
